package com.xyw.code.taobaokeapi.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.TbkDgMaterialOptionalRequest;
import com.taobao.api.request.TbkItemInfoGetRequest;
import com.taobao.api.request.TbkTpwdCreateRequest;
import com.taobao.api.response.TbkDgMaterialOptionalResponse;
import com.taobao.api.response.TbkItemInfoGetResponse;
import com.taobao.api.response.TbkTpwdCreateResponse;
import com.xyw.code.common.core.exception.BaseException;
import com.xyw.code.taobaokeapi.service.TbkService;
import com.xyw.code.taobaokeapi.util.TbkUtil;
import com.xyw.common.taobaokecommon.enums.AlimamaConstant;
import com.xyw.common.taobaokecommon.enums.TaobaokeErrorType;
import com.xyw.common.taobaokecommon.util.HttpUtil;
import com.xyw.common.taobaokecommon.vo.CommissionInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * Created with IntelliJ IDEA.
 * User: xuyiwei
 * Date: 2020/8/5
 * Time: 下午3:40
 * Email: 1328312923@qq.com
 * Description: No Description
 **/
@Service
@Slf4j
public class TbkServiceImpl implements TbkService {
    @Override
    public String getUrlByShare(String token) {
        return TbkUtil.getUrlByToken(token);
    }

    @Override
    public String getTklByShare(String token) {
        return TbkUtil.getTkl(token);
    }

    @Override
    public TbkDgMaterialOptionalResponse queryMaterial(String token) {
        TaobaoClient client = new DefaultTaobaoClient(AlimamaConstant.serverUrl,
                AlimamaConstant.appKey, AlimamaConstant.appSecret);
        TbkDgMaterialOptionalRequest req = new TbkDgMaterialOptionalRequest();
        req.setQ(token);
        req.setAdzoneId(AlimamaConstant.adzoneId);
        TbkDgMaterialOptionalResponse rsp = null;
        try {
            rsp = client.execute(req);
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return rsp;
    }

    @Override
    public TbkItemInfoGetResponse queryByProductId(String productId)  {
        TaobaoClient client = new DefaultTaobaoClient(AlimamaConstant.serverUrl,
                AlimamaConstant.appKey, AlimamaConstant.appSecret);
        TbkItemInfoGetRequest req = new TbkItemInfoGetRequest();
        req.setNumIids(productId);
        req.setPlatform(1L);
        try{
            TbkItemInfoGetResponse rsp = client.execute(req);
            return rsp;
        }catch (Exception e){
            log.error("获取物料信息简版出现bug");
        }
        return null;
     }

    @Override
    public String getCouponTklByUrl(String text,String url,String logo) {
        if(!url.contains("https:")){
            url = "https:"+url;
        }
        TaobaoClient client = new DefaultTaobaoClient(AlimamaConstant.serverUrl,
                AlimamaConstant.appKey, AlimamaConstant.appSecret);
        TbkTpwdCreateRequest req = new TbkTpwdCreateRequest();
        req.setText(text);
        req.setUrl(url);
        req.setLogo(logo);
        req.setExt("{}");
        TbkTpwdCreateResponse rsp = null;
        try {
            rsp = client.execute(req);
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return rsp.getData().getModel();
    }

    @Override
    public Double getCommissionPrice(String zkFinalPriceStr,String couponAmountStr,
                                     String commissionRateStr) {
        //得到折扣价格
        Double zkFinalPrice = Double.parseDouble(zkFinalPriceStr);
        //得到折扣价格
        Double couponAmount = Double.parseDouble(couponAmountStr==null?"0":couponAmountStr);
        //得到佣金
        Double commissionRate = Double.parseDouble(commissionRateStr==null?"0":commissionRateStr);
        Double commission = (zkFinalPrice-couponAmount)*(commissionRate/10000);

        return commission<0?0D:commission;
    }

    @Override
    public CommissionInfoVO getCommissionInfo(String token) {
        CommissionInfoVO commissionInfoVO = new CommissionInfoVO();
        String url = TbkUtil.getRealUrlByToken(token);
        //如果url是空
        if(StringUtils.isBlank(url)){
            String tkl =  TbkUtil.getTkl(token);
            String result = HttpUtil.doGet("http://www.taofake.com/index/tools/gettkljm.html?tkl="+tkl);
            JSONObject object = JSONObject.parseObject(result);
            url = object.getJSONObject("data").getString("url");
        }
        //根据淘口令获得商品详情
        TbkDgMaterialOptionalResponse optionalResponse =queryMaterial(url);
        //获得商品size
        Long totalResult = Optional.ofNullable(optionalResponse.getTotalResults()).orElse(0L);
        if( totalResult == 0){
            log.error("物料详情为空");
            return null;
            //throw new BaseException(TaobaokeErrorType.MATERIALOPTIONAL_NULL);
        }
        //如果有的话  取第一个
        TbkDgMaterialOptionalResponse.MapData data =  optionalResponse.getResultList().get(0);
        if(data==null){
            log.error("物料详情为空");
            return null;
            //throw new BaseException(TaobaokeErrorType.MATERIALOPTIONAL_NULL);
        }
        covertFanliVO(data,commissionInfoVO);
        return commissionInfoVO;
    }

    @Override
    public Boolean isHaveCommission(CommissionInfoVO commissionInfoVO) {
        String couponShareUrl = commissionInfoVO.getCouponShareUrl();
        return StringUtils.isBlank(couponShareUrl)?false:true;
    }


    /**
     * 转换返利vo
     * @param data
     * @param commissionInfoVO
     */
    private CommissionInfoVO covertFanliVO(TbkDgMaterialOptionalResponse.MapData data, CommissionInfoVO commissionInfoVO) {
        BeanUtils.copyProperties(data,commissionInfoVO);
        //得到返利金额
        Double commissionPrice = getCommissionPrice(data.getZkFinalPrice(),data.getCouponAmount(),data.getCommissionRate());
        commissionInfoVO.setCommissionPrice(commissionPrice);
        commissionInfoVO.setZkFinalPrice(Double.parseDouble(data.getZkFinalPrice()));
        commissionInfoVO.setCouponAmount(Double.parseDouble(data.getCouponAmount()==null?"0":data.getCouponAmount()));
        //得到优惠券淘口令
        if(StringUtils.isNotBlank(data.getCouponShareUrl())){
            String couponTkl = getCouponTklByUrl(data.getCouponAmount()+"面额优惠券",data.getCouponShareUrl(),data.getSmallImages().size()>0?data.getSmallImages().get(0):"");
            commissionInfoVO.setCouponTkl(couponTkl);
        }
        //得到商品淘口令
        String urlTkl = getCouponTklByUrl( data.getTitle(),data.getUrl(),data.getSmallImages()!=null?data.getSmallImages().get(0):"");
        commissionInfoVO.setUrlTkl(urlTkl);
        return commissionInfoVO;
    }

    @Override
    public String covertTkl(CommissionInfoVO commissionInfoVO) {
        String respContent = "没有该商品信息";

        if(commissionInfoVO!=null){
            DecimalFormat df = new DecimalFormat("0.00");
            Double commissionPrice = Double.parseDouble(df.format(commissionInfoVO.getCommissionPrice()==null?0d:commissionInfoVO.getCommissionPrice()/2));
            //如果有优惠券
            if(isHaveCommission(commissionInfoVO)){
                respContent = "返利金额:"+(commissionPrice<1?(0):commissionPrice)+",优惠券:￥"+commissionInfoVO.getCouponAmount()+",淘口令"+commissionInfoVO.getCouponTkl();
            }else{
                respContent = "返利金额:"+(commissionPrice<1?(0):commissionPrice)+",优惠券:无,淘口令"+commissionInfoVO.getUrlTkl();
            }
        }

        return respContent;
    }
}
